package com.jinbiao.quasar.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.dto.RoleApiDto;
import com.jinbiao.quasar.dto.RoleDto;
import com.jinbiao.quasar.dto.RolePermissionDto;
import com.jinbiao.quasar.dto.UserRoleDto;
import com.jinbiao.quasar.enums.DeptDataPermissionType;
import com.jinbiao.quasar.model.*;
import com.jinbiao.quasar.util.AjaxJson;
import com.jinbiao.quasar.util.ListUtil;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.data.annotation.Tran;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.EntityQuery;
import org.sagacity.sqltoy.model.EntityUpdate;
import org.sagacity.sqltoy.model.Page;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@OperationLog
public class RoleController {
    @Db
    SqlToyLazyDao dao;
    @Mapping("/role/get-role-list")
    public AjaxJson getRoleList(int page,int pageSize,String sortBy,boolean desc,SysRole sysRole){
        EntityQuery entityQuery = EntityQuery.create().where("#[and role_group like :roleGroup]\n" +
                "            #[and role_method like :roleMethod]\n" +
                "            #[and role_path like :rolePath]").values(sysRole);
        Page<RoleDto> pageResult =  dao.findPageEntity(new Page(pageSize,page),SysRole.class, desc?entityQuery.orderByDesc(sortBy):entityQuery.orderBy(sortBy),RoleDto.class);
        pageResult.getRows().stream().forEach(item->{
            SysMenu filter= new SysMenu();
            filter.setName(item.getDefaultPage());
            List<SysMenu> menus = dao.findBySql("sysMenuList",filter);
            if(CollectionUtil.isNotEmpty(menus)) item.setDefaultPageMenu(menus.get(0));
        });
        return AjaxJson.getSuccessData(pageResult);
    }

    @Mapping("/role/delete-role-by-id")
    public AjaxJson deleteRoleById(SysRole sysRole){
        return AjaxJson.getSuccessData(dao.delete(sysRole));
    }

    @Mapping("/role/edit-role")
    public AjaxJson editRole(SysRole sysRole){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysRole));
    }

    @Mapping("/role/add-role")
    public AjaxJson addRole(SysRole sysRole){
        sysRole.setDeptDataPermissionType(DeptDataPermissionType.USER.getCode());
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysRole));
    }

    @Mapping("/role/query-role-by-id")
    public AjaxJson queryRoleById(SysRole sysRole){
        List<SysRole> results = dao.findBySql("sysRoleList",sysRole);
        if(CollectionUtil.isNotEmpty(results)){
            SysRole role = results.get(0);
            return AjaxJson.getSuccessData(role);
        }
        return AjaxJson.getSuccessData(null);
    }

    @Mapping("/public/get-role-all")
    public AjaxJson getRoleAll(SysRole sysRole){
        return AjaxJson.getSuccessData(dao.findBySql("sysRoleList",sysRole));
    }

    @Mapping("/role/get-role-menu-list")
    public AjaxJson getRoleMenuList(SysRoleMenu roleMenu){
        return AjaxJson.getSuccessData(dao.findBySql("getRoleMenuList", BeanUtil.beanToMap(roleMenu,"roleCode"),SysRoleMenu.class));
    }

    @Mapping("/role/get-role-button-list")
    public AjaxJson getRoleButtonList(SysRoleButton roleButton){
        return AjaxJson.getSuccessData(dao.findBySql("getRoleButtonList",BeanUtil.beanToMap(roleButton,"roleCode"), SysRoleButton.class));
    }

    @Mapping("/role/edit-role-dept-data-permission")
    public AjaxJson editRoleDeptDataPermission(SysRole sysRole){
        Long result = dao.updateByQuery(SysRole.class, EntityUpdate.create()
                .set("deptDataPermissionType",sysRole.getDeptDataPermissionType())
                .set("deptDataPermissionCustom",sysRole.getDeptDataPermissionCustom())
                .where("role_code=?").values(sysRole.getRoleCode()));
        return result>0?AjaxJson.getSuccess():AjaxJson.getError("修改失败");
    }

    @Mapping("/role/get-role-api-list")
    public AjaxJson getRoleApiList(SysRoleApi roleApi){
        return AjaxJson.getSuccessData(dao.findBySql("sysRoleApiList",BeanUtil.beanToMap(roleApi,"roleCode"), SysRoleApi.class));
    }

    @Mapping("/role/edit-role-api")
    @Tran
    public AjaxJson editRoleApi(RoleApiDto roleApiDto){
        dao.deleteByQuery(SysRoleApi.class,EntityQuery.create().where("role_code = ?").values(roleApiDto.getRoleCode()));
        dao.saveAll(roleApiDto.getRoleApi());
        return AjaxJson.getSuccess("修改成功");
    }

    @Mapping("/role/edit-role-menu")
    @Tran
    public AjaxJson editRoleMenu(RolePermissionDto rolePermissionDto){
        List<SysRoleMenu> roleMenus = rolePermissionDto.getRoleMenu();
        List<SysRoleButton> roleButtons = rolePermissionDto.getRoleButton();
        String roleCode = rolePermissionDto.getRoleCode();
        String defaultPage = rolePermissionDto.getDefaultPage();
        dao.deleteByQuery(SysRoleMenu.class,EntityQuery.create().where("sys_role_role_code = ?").values(roleCode));
        dao.deleteByQuery(SysRoleButton.class,EntityQuery.create().where("sys_role_role_code = ?").values(roleCode));
        dao.saveAll(roleMenus);
        dao.saveAll(roleButtons);
        dao.updateByQuery(SysRole.class,EntityUpdate.create().set("defaultPage",defaultPage).where("role_code=?").values(roleCode));
        return AjaxJson.getSuccess("修改成功");
    }

    @Mapping("/role/query-user-by-role")
    public AjaxJson queryUserByRole(int page,int pageSize,String sortBy,boolean desc,SysUserRole sysUserRole){
        return AjaxJson.getSuccessData(dao.findPageBySql(new Page(pageSize,page),"getRoleUserList",BeanUtil.beanToMap(sysUserRole,"roleCode"),SysUser.class));
    }

    @Mapping("/role/add-role-user")
    public AjaxJson addRoleUser(UserRoleDto userRoleDto){
        List<SysUserRole> list = dao.findBySql("sysUserRoleList",new SysUserRole(userRoleDto.getRoleCode()));
        if(CollectionUtil.isNotEmpty(userRoleDto.getUsername())){
            List<String> exists = list.stream().map(SysUserRole::getUsername).collect(Collectors.toList());
            List<String> toAdd = ListUtil.getDiffrentList(exists,userRoleDto.getUsername());
            if(CollectionUtil.isNotEmpty(toAdd)){
                List<SysUserRole> userRoleList = new ArrayList<>();
                toAdd.stream().forEach(item->{
                    userRoleList.add(new SysUserRole(userRoleDto.getRoleCode(),item));
                });
                dao.saveAll(userRoleList);
                return AjaxJson.getSuccess(
                        userRoleDto.getUsername().size()==toAdd.size()?
                                StrUtil.format("新增{}条记录成功",toAdd.size()):
                        StrUtil.format("新增{}成功，另外{}条记录已经存在",toAdd.size(),userRoleDto.getUsername().size()-toAdd.size()));
            }else{
                return AjaxJson.getError("增加的人员全部已经存在！");
            }
        }
        return AjaxJson.getError("传入参数错误");
    }

    @Mapping("/role/remove-role-user")
    public AjaxJson removeRoleUser(SysUserRole userRole){
        dao.deleteByQuery(SysUserRole.class,EntityQuery.create().where("sys_role_role_code = ? and sys_user_username = ?").values(userRole.getRoleCode(),userRole.getUsername()));
        return AjaxJson.getSuccess("处理成功");
    }
}
